<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>编辑函数</title>
    <link rel="stylesheet" data-name="vs/editor/editor.main" href="https://cdn.jsdelivr.net/npm/monaco-editor@0.44.0/min/vs/editor/editor.main.min.css">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>body{padding:2em;}</style>
</head>
<body>
    <h3>编辑函数：<span id="funcName"></span></h3>
    <div id="editor" style="height:400px;border:1px solid #ccc;"></div>
    <button class="btn btn-success mt-3" onclick="saveFunc()">保存</button>
    <a href="/" class="btn btn-secondary mt-3 ms-2">返回主页</a>
    <script src="https://cdn.jsdelivr.net/npm/monaco-editor@0.44.0/min/vs/loader.min.js"></script>
    <script>
    let funcId = new URLSearchParams(location.search).get('id');
    let userId = new URLSearchParams(location.search).get('user_id');
    let editor;
    // 获取函数详情
    fetch(`/user_functions?user_id=${userId}`).then(r=>r.json()).then(funcs=>{
        let func = funcs.find(f=>f.id==funcId);
        document.getElementById('funcName').textContent = func.func_name;
        require.config({ paths: { 'vs': 'https://cdn.jsdelivr.net/npm/monaco-editor@0.44.0/min/vs' }});
        require(['vs/editor/editor.main'], function() {
            editor = monaco.editor.create(document.getElementById('editor'), {
                value: func.func_code,
                language: 'python',
                theme: 'vs-light',
                automaticLayout: true
            });
        });
    });
    function saveFunc() {
        fetch('/user_functions', {
            method: 'POST',
            headers: {'Content-Type':'application/json'},
            body: JSON.stringify({
                user_id: userId,
                id: funcId,
                func_name: document.getElementById('funcName').textContent,
                func_code: editor.getValue(),
                update: true
            })
        }).then(r=>r.json()).then(res=>{
            if(res.error) alert(res.error);
            else alert('保存成功');
        });
    }
    </script>
</body>
</html> 